/**
 * Created by lumix on 2015/5/26.
 */
var Promise = require('promise');
var logger = require('log4js').getLogger('12LingService_s01e01');
var db = require('../../../utils/db/mysqlDb');
var comm = require('../../../utils/commonUtils');
var likeService = require('../../common/service/LikeService');
var likeCollectService = require('../../common/service/LikeCollectService');
var prizeService = require('../../common/service/PrizeService');
var recordService = require('../../common/service/RecordService');
var redisDb = require("./../../../utils/db/redisDb");
var tempService_s01e01 = {};

tempService_s01e01.getLikeById = function (id) {
    if (id) {
        return likeService.getById(id);
    } else {
        return Promise.resolve(null);
    }
};

tempService_s01e01.getLikeByParams = function (params) {
    return new Promise(function (fulfill, reject) {
        likeService.getByParams(params, "id").then(function (r) {
            if (r.length > 0) {
                fulfill(r[0]);
            } else {
                fulfill(null);
            }
        }, function (err) {
            reject(err);
        })
    });
};

tempService_s01e01.saveLike = function (like) {
    return likeService.save(like);
};

tempService_s01e01.getCollectors = function (params) {
    return likeCollectService.getByParams(params, "id");
};

tempService_s01e01.lottery = function (like, fans) {
    return new Promise(function (fulfill, reject) {
        var p = {settingId: settingId, level: level, state: 0};
        prizeService.getPrize("12Ling_PRIZE_S01E01", p).then(function (prize) {
            like.collect -= 200;
            var record = {settingId: like.settingId, openid: fans.openId, createTime: new Date()};
            if (prize) {
                prize.state = 1;
                record.prizeId = prize.id;
            } else {
                record.prizeId = -1;
            }
            return _updateLottery(like, prize, record);
        }).then(function (r) {
            var result = {};
            result.like = r[0];
            result.prize = r[1];
            result.record = r[2];
            fulfill(result);
        }, function (err) {
            reject(err);
        });
    })
};

tempService_s01e01.addScore = function (f_like, own_like, score) {
    return new Promise(function (fulfill, reject) {
        db.getConnection().then(function (conn) {
            db.beginTransaction(conn).then(function () {
                f_like.collect += score;
                own_like.collect += score;
                var f_collect = {
                    settingId: f_like.settingId, likeId: f_like.id,
                    sponsorOpenid: f_like.sponsorOpenid, actorOpenid: own_like.sponsorOpenid,
                    count: score, content: own_like.name, result: own_like.remarks, createTime: new Date()
                };
                var own_collect = {
                    settingId: own_like.settingId, likeId: own_like.id,
                    sponsorOpenid: own_like.sponsorOpenid, actorOpenid: own_like.sponsorOpenid,
                    count: score, content: own_like.name, result: own_like.remarks, createTime: new Date()
                };

                return Promise.all([
                    likeService.update(f_like, conn),
                    likeService.update(own_like, conn),
                    likeCollectService.save(f_collect, conn),
                    likeCollectService.save(own_collect, conn)
                ]);
            }).then(function () {
                db.commit(conn);
                fulfill(true);
            }, function (err) {
                logger.error(err);
                db.rollback(conn);
                reject(false);
            })
        }, function (err) {
            reject(err)
        })
    })
};

tempService_s01e01.addMyScore = function (like, score) {
    return new Promise(function (fulfill, reject) {
        db.getConnection().then(function (conn) {
            db.beginTransaction(conn).then(function () {
                like.collect += score;
                var collect = {
                    settingId: like.settingId, likeId: like.id,
                    sponsorOpenid: like.sponsorOpenid, actorOpenid: like.sponsorOpenid,
                    count: score, content: like.name, result: like.remarks, createTime: new Date()
                };
                return Promise.all([
                    likeService.update(like, conn),
                    likeCollectService.save(collect, conn)
                ]);
            }).then(function () {
                db.commit(conn);
                fulfill(true);
            }, function (err) {
                logger.error(err);
                db.rollback(conn);
                reject(false);
            })
        }, function (err) {
            reject(err)
        })
    })
};

function getPrizeNums(settingId) {
    return new Promise(function (fullful, reject) {
        var key = '12Ling_S01e01_PrizeNum' + settingId;
        var result = {selectFlag: true};
        redisDb.get(key).then(function (redisObject) {
            if (redisObject) {
                var _tempObj = JSON.parse(redisObject);
                if (isInvalid(_tempObj.time, 5)) {
                    result.prizeNums = _tempObj.prizeNums;
                    result.selectFlag = false;
                }
            }
        }).then(function () {
            if (result.selectFlag) {
                return Promise.all([
                    prizeService.count({settingId: settingId, level: 1, state: 0}),
                    prizeService.count({settingId: settingId, level: 2, state: 0}),
                    prizeService.count({settingId: settingId, level: 3, state: 0}),
                    prizeService.count({settingId: settingId, level: 4, state: 0}),
                    prizeService.count({settingId: settingId, level: 5, state: 0}),
                    prizeService.count({settingId: settingId, level: 6, state: 0}),
                    prizeService.count({settingId: settingId, level: 7, state: 0}),
                    prizeService.count({settingId: settingId, level: 8, state: 0}),
                    prizeService.count({settingId: settingId, level: 9, state: 0})
                ]).then(function (_prizeNums) {
                    var prize1 = {num: _prizeNums[0], level: 1, worth: 15000, flag: false, type: 1};
                    var prize2 = {num: _prizeNums[1], level: 2, worth: 45000, flag: false, type: 1};
                    var prize3 = {num: _prizeNums[2], level: 3, worth: 90000, flag: false, type: 1};
                    var prize4 = {num: _prizeNums[3], level: 4, worth: 180000, flag: false, type: 1};
                    var prize5 = {num: _prizeNums[4], level: 5, worth: 180000, flag: false, type: 1};
                    var prize6 = {num: _prizeNums[5], level: 6, worth: 300000, flag: false, type: 1};
                    var prize7 = {num: _prizeNums[6], level: 7, worth: 400000, flag: false, type: 1};
                    var prize8 = {num: _prizeNums[7], level: 8, worth: 400000, flag: false, type: 1};
                    var prize9 = {num: _prizeNums[8], level: 9, worth: 600000, flag: false, type: 1};
                    var prizeNums = {
                        prize1: prize1,
                        prize2: prize2,
                        prize3: prize3,
                        prize4: prize4,
                        prize5: prize5,
                        prize6: prize6,
                        prize7: prize7,
                        prize8: prize8,
                        prize9: prize9
                    };

                    result.prizeNums = prizeNums;
                    var _tempObj = {prizeNums: prizeNums, time: new Date().getTime()};
                    redisDb.setex(key, JSON.stringify(_tempObj), 5);
                    return Promise.resolve(result.prizeNums);
                });
            } else {
                return Promise.resolve(result.prizeNums);
            }
        }).then(function (_result) {
            fullful(_result);
        }, function (err) {
            logger.error(err);
            reject(err);
        });
    });
}

tempService_s01e01.getMyChateau = function (settingId, openId) {
    return new Promise(function (fulfill, reject) {
        var result = {};
        getPrizeNums(settingId).then(function (_prizeNums) {
            result.prizeNums = _prizeNums;
        }).then(function () {
            return recordService.getByParams({settingId: settingId, openid: openId}, "id").then(function (records) {
                records.forEach(function (item) {
                    if (item.score == 1) {
                        result.prizeNums.prize1.flag = true;
                        result.prizeNums.prize1.record = item;
                    } else if (item.score == 2) {
                        result.prizeNums.prize2.flag = true;
                        result.prizeNums.prize2.record = item;
                    } else if (item.score == 3) {
                        result.prizeNums.prize3.flag = true;
                        result.prizeNums.prize3.record = item;
                    } else if (item.score == 4) {
                        result.prizeNums.prize4.flag = true;
                        result.prizeNums.prize4.record = item;
                    } else if (item.score == 5) {
                        result.prizeNums.prize5.flag = true;
                        result.prizeNums.prize5.record = item;
                    } else if (item.score == 6) {
                        result.prizeNums.prize6.flag = true;
                        result.prizeNums.prize6.record = item;
                    } else if (item.score == 7) {
                        result.prizeNums.prize7.flag = true;
                        result.prizeNums.prize7.record = item;
                    } else if (item.score == 8) {
                        result.prizeNums.prize8.flag = true;
                        result.prizeNums.prize8.record = item;
                    } else if (item.score == 9) {
                        result.prizeNums.prize9.flag = true;
                        result.prizeNums.prize9.record = item;
                    }
                });
                return Promise.resolve(result);
            });
        }).then(function (_result) {
            fulfill(_result);
        }, function (err) {
            reject(err);
        });
    });
};

tempService_s01e01.cashPrize = function (like, record) {
    return new Promise(function (fulfill, reject) {
        var result = {lottery: false, cashFlag: false, msg: ""};
        var _tempWorth = 0;
        var key = '12Ling_S01e01_PrizeNum' + like.settingId;
        getPrizeNums(like.settingId).then(function (prizeNums) {
            result.prizeNums = prizeNums;
        }).then(function () {
            return recordService.getByParams({settingId: like.settingId, openid: like.sponsorOpenid}, "id").then(function (records) {
                var _temp = true;
                records.forEach(function (item) {
                    if (item.score == record.score) {
                        _temp = false;
                        result.msg = "该奖品已经兑换过！"
                    }
                });
                return Promise.resolve(_temp);
            });
        }).then(function (_temp) {
            if (!_temp) {
                return Promise.resolve(null);
            }
            if (record.score == 1 && like.collect >= result.prizeNums.prize1.worth) {
                result.lottery = true;
                _tempWorth = result.prizeNums.prize1.worth;
                result.prizeNums.prize1.num--;
            } else if (record.score == 2 && like.collect >= result.prizeNums.prize2.worth) {
                result.lottery = true;
                _tempWorth = result.prizeNums.prize2.worth;
                result.prizeNums.prize2.num--;
            } else if (record.score == 3 && like.collect >= result.prizeNums.prize3.worth) {
                result.lottery = true;
                _tempWorth = result.prizeNums.prize3.worth;
                result.prizeNums.prize3.num--;
            } else if (record.score == 4 && like.collect >= result.prizeNums.prize4.worth) {
                result.lottery = true;
                _tempWorth = result.prizeNums.prize4.worth;
                result.prizeNums.prize4.num--;
            } else if (record.score == 5 && like.collect >= result.prizeNums.prize5.worth) {
                result.lottery = true;
                _tempWorth = result.prizeNums.prize5.worth;
                result.prizeNums.prize5.num--;
            } else if (record.score == 6 && like.collect >= result.prizeNums.prize6.worth) {
                result.lottery = true;
                _tempWorth = result.prizeNums.prize6.worth;
            } else if (record.score == 7 && like.collect >= result.prizeNums.prize7.worth) {
                result.lottery = true;
                _tempWorth = result.prizeNums.prize7.worth;
                result.prizeNums.prize7.num--;
            } else if (record.score == 8 && like.collect >= result.prizeNums.prize8.worth) {
                result.lottery = true;
                _tempWorth = result.prizeNums.prize8.worth;
                result.prizeNums.prize8.num--;
            } else if (record.score == 9 && like.collect >= result.prizeNums.prize9.worth) {
                result.lottery = true;
                _tempWorth = result.prizeNums.prize9.worth;
                result.prizeNums.prize9.num--;
            }

            if (result.lottery) {
                var p = {settingId: like.settingId, level: record.score, state: 0};
                return prizeService.getPrize("12Ling_PRIZE_S01E01", p).then(function (prize) {
                    if (prize) {
                        prize.state = 1;
                        record.prizeId = prize.id;
                        record.prizeName = prize.name;
                        record.remarks = prize.content;
                        result.prize = prize;
                    } else {
                        result.msg = "奖品不足";
                    }
                });
            } else {
                result.msg("积分不足");
            }
        }).then(function () {
            if (result.lottery && result.prize) {
                like.collect -= _tempWorth;
                return _updateLottery(like, result.prize, record).then(function (res) {
                    if (!!res) {
                        result.cashFlag = true;
                        result.record = record;
                    }
                }).then(function () {
                    var _tempObj = {prizeNums: result.prizeNums, time: new Date().getTime()};
                    redisDb.setex(key, JSON.stringify(_tempObj), 5);
                    return Promise.resolve(result);
                });
            } else {
                return Promise.resolve(result);
            }
        }).then(function (_result) {

            fulfill(_result);
        }, function (error) {
            reject(error);
        });
    });
};


tempService_s01e01.getFriendCollects = function (like) {
    return new Promise(function (fulfill, reject) {
        var params = {settingId: like.settingId, likeId: like.id};
        likeCollectService.getByParams(params, "id").then(function (collects) {
            var _tempMap = {};
            var _tempArray = new Array();
            collects.forEach(function (item) {
                if (item.sponsorOpenid != item.actorOpenid) {
                    var _temp = "_tempMap.id" + item.id + ' = "' + item.content + "|" + item.result + "|" + item.count + '";'
                    logger.debug("VALUE:" + _temp);
                    eval(_temp);
                }
            });
            logger.debug("------------------------------------------_tempMap----------------------------------------");
            logger.debug(_tempMap);
            for (var key in _tempMap) {
                if (!(typeof(_tempMap[key]) == "function")) {
                    var _temp = _tempMap[key].split("|")
                    _tempArray.push(_temp);
                }
            }
            logger.debug(_tempArray);
            return Promise.resolve(_tempArray);
        }).then(function (result) {
            fulfill(result);
        }, function (err) {
            logger.error(err);
            reject(err);
        });
    });
};

tempService_s01e01.updateLike = function (like) {
    return new Promise(function (fulfill, reject) {
        likeService.update(like).then(function (r) {
            fulfill(r);
        }, function (err) {
            reject(err);
        })
    });
};

//function map_put(key, value) {
//    var s = "map." + key + ' = "' + value + '";';
//    eval(s);
//}
//
//function map_get (key) {
//    var v = eval("map." + key + ";");
//    return v;
//}
//
//function map_keySet() {
//    var keySets = new Array();
//    for (var key in map) {
//        if (!(typeof(map[key]) == "function")) {
//            keySets.push(key);
//        }
//    }
//    return keySets;
//}


function _updateLottery(like, prize, record) {
    return new Promise(function (fulfill, reject) {
        db.getConnection().then(function (conn) {
            db.beginTransaction(conn).then(function () {
                var array = new Array();
                array.push(likeService.update(like, conn));
                if (prize) {
                    array.push(prizeService.update(prize, conn));
                } else {
                    array.push(Promise.resolve(null));
                }
                array.push(recordService.save(record, conn));
                return Promise.all(array);
            }).then(function (r) {
                db.commit(conn);
                fulfill(r);
            }, function (err) {
                db.rollback(conn);
                reject(err);
            })
        }, function (err) {
            reject(err);
        })
    })
}

function isInvalid(redisTime, invalidSecond) {
    var _temp = new Date().getTime() - parseInt(redisTime);
    if (_temp < invalidSecond * 1000) {
        return true;
    } else {
        return false;
    }
}


module.exports = tempService_s01e01;